import { post, get } from 'server/axios.js'
import { config_list_column_post } from 'server/modules/1890.js'
import Storage from 'utils/Storage.js'
// 定义filter 本地存储key
const STORAGE_FILTER_KEY = 'VXE_COLUMNS_STORAGE_FILTER'

export const useInitState = (props, state) => {
  // 默认获取本地的storage
  const { clearStorageFilter, getStorageFilter } = useStorageFilter(
    props,
    state
  )
  clearStorageFilter()
  Object.assign(state, {
    query: {
      sortList: [],
      ...getStorageFilter(),
      ...props.queryParams
    }
  })
}
/**
 * 处理表格筛选条件本地存储
 * @param {*} props
 * @param {*} state
 */
const useStorageFilter = (props, state) => {
  const { menuName } = props
  const { query } = state
  const storage = Storage.getItem(STORAGE_FILTER_KEY) || {}
  const clearStorageFilter = () => {
    if (!props.filterStorage) {
      delete storage[menuName]
      Storage.setItem(STORAGE_FILTER_KEY, storage)
    }
  }
  const setStorageFilter = () => {
    if (props.filterStorage) {
      storage[menuName] = query
      Storage.setItem(STORAGE_FILTER_KEY, storage)
    }
  }
  const getStorageFilter = () => {
    return storage[menuName] || {}
  }
  return {
    clearStorageFilter,
    setStorageFilter,
    getStorageFilter
  }
}
// 接口拉取服务端数据
export const executeServer = async function (state, props) {
  const { interfaceURL, localApiParams, query, hasPaginate } = state
  if (!state.interfaceURL) {
    return false
  }
  state.spinning = true
  const { setStorageFilter } = useStorageFilter(props, state)

  let paginate = {}
  if (hasPaginate) {
    paginate = {
      pageNum: state.pageNum,
      pageSize: state.pageSize
    }
  }
  const serveParams = {
    ...paginate,
    ...localApiParams,
    ...query
  }
  setStorageFilter()

  if (state.beforeReqLoad) {
    state.beforeReqLoad(serveParams)
  }
  const fn = state.method === 'get' ? get : post
  try {
    const { success, data } = await fn(
      `${process.env.VUE_APP_CONFIG}/${interfaceURL}`,
      serveParams
    )
    state.spinning = false
    if (success) {
      if (Object.prototype.toString.call(data) === '[object Object]') {
        state.tableDatas = data.list || []
      } else {
        state.tableDatas = data || []
      }

      state.total = data?.total || 0
      // pageInfo.pageSize = data.pageSize
    } else {
      state.tableDatas = []
    }
    if (props && props.afterRespLoad) {
      props.afterRespLoad(state.tableDatas)
    }
  } catch (error) {
    console.error(error)
    state.spinning = false
  }
}
/**
 * 拉取每个列的筛选数据
 * @param {*} item
 */
export const getConfigColumn = async function (item, state) {
  state.loading = true
  const result = await config_list_column_post(item.params)
  if (state.query[item.key] && state.query[item.key].length > 0) {
    item.filterValue = state.query[item.key] || []
  }
  if (item.searchValue) {
    item.plainOptions = result.data.filter(
      t =>
        t.value &&
        t.value.toLowerCase().includes(item.searchValue.trim().toLowerCase())
    )
  } else {
    item.plainOptions = result.data
  }
  state.options = result.data
  state.loading = false
}
/**
 * 获取用户选择的条件参数
 * @param {*} state
 */
export const getFilterParams = function (state, props) {
  const query = { sortList: [] }
  state.tableColumns.forEach(_ => {
    if (_.desc) {
      query.sortList.push({
        desc: _.desc,
        field: _.dataIndex
      })
    }
    if (_.isBatch) {
      query[_.key] = _.batchTags
    } else {
      if (_.needEmpty === 1) {
        if (_.isBlank) {
          const index = _.filterValue.findIndex(item => item === '')
          index === -1 && _.filterValue.push('')
        } else {
          _.filterValue = _.filterValue.filter(v => v !== '')
        }
      }
      if (_.filterValue && _.filterValue.length) {
        query[_.key] = _.filterValue
      }
    }
  })
  state.query = query
  localStorage.setItem(`${props.menuName}Query`, JSON.stringify(query))
}
export const executeSearch = function (state, props) {
  getFilterParams(state, props)
  executeServer(state, props)
}
/**
 * 根据列标题获取列宽
 * @param {*} column
 * @returns
 */
export const useColumnWidth = (column, state) => {
  const { title: columnName, width, slots, dataIndex } = column
  const { columnWidth = {} } = state
  if (width) {
    return width
  }
  if (columnWidth[dataIndex]) {
    return columnWidth[dataIndex]
  }

  let fixedWidth = 0
  for (let i = 0; i < columnName.length; i++) {
    const charCode = columnName.charCodeAt(i)
    if (charCode >= 0 && charCode <= 128) {
      fixedWidth += 8
    } else {
      fixedWidth += 16
    }
  }
  // 添加两边的间距 5是误差
  fixedWidth += 16 + 5
  //  有筛选
  if (slots?.filterDropdown === 1) {
    fixedWidth += 28
  }
  if (fixedWidth < 160) {
    return 160
  }
  if (fixedWidth > 320) {
    return 320
  }
  return fixedWidth
}
